package zone

import (
	"github.com/Unixeno/TheMoon/moon/zone/storage"
	"sync"
)

var localDeployers sync.Map

func initLocalDeployers() {
	deployers := storage.ListLocalDeployer()
	for id, d := range deployers {
		localDeployers.Store(id, &deployer{
			zoneID:        id,
			version:       d.Version,
			containers:    d.Containers,
			volumes:       d.Volumes,
			networks:      d.Networks,
			spinlock:      new(int32),
			islandsClient: islandsClient,
		})
	}
}

func loadOrCreateDeployer(zoneID string) *deployer {
	d, _ := localDeployers.LoadOrStore(zoneID, &deployer{
		zoneID:        zoneID,
		version:       0,
		containers:    make(map[string]string),
		volumes:       make(map[string]string),
		networks:      make(map[string]string),
		islandsClient: islandsClient,
		spinlock:      new(int32),
	})
	return d.(*deployer)
}

func getDeployer(zoneID string) (*deployer, bool) {
	d, ok := localDeployers.Load(zoneID)
	if ok {
		return d.(*deployer), ok
	}
	return nil, ok
}

func saveDeployer(d *deployer) {
	storage.PutLocalDeployer(d.zoneID, storage.LocalDeployer{
		ZoneID:     d.zoneID,
		Version:    d.version,
		Containers: d.containers,
		Volumes:    d.volumes,
		Networks:   d.networks,
	})
}

func deleteDeployer(d *deployer) {
	localDeployers.Delete(d.zoneID)
	storage.DeleteLocalDeployer(d.zoneID)
}
